package com.yami.shop.cp.api.controller;


import cn.hutool.core.util.StrUtil;
import com.yami.shop.bean.app.dto.OrderNumbersDto;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.model.Order;
import com.yami.shop.cp.comment.param.CPOrderParam;
import com.yami.shop.cp.comment.service.CPOrderService;
import com.yami.shop.security.api.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/p/cp/order")
@Api(tags = "协同采购订单接口")
@AllArgsConstructor
public class CPOrderController {

    private CPOrderService cpOrderService;

    @PostMapping("/submit")
    @ApiOperation(value = "结算，生成订单信息并提交订单", notes = "传入下单所需要的参数进行下单")
    public ResponseEntity<OrderNumbersDto> confirm(@Valid @RequestBody CPOrderParam cpOrderParam) {
        String userId = SecurityUtils.getUser().getUserId();
        if (Objects.isNull(cpOrderParam.getDvyType())) {
            cpOrderParam.setDvyType(DvyType.DELIVERY.value());
        }

        List<Order> orders = cpOrderService.submit(userId, cpOrderParam);
        StringBuilder orderNumbers = new StringBuilder();
        for (Order order : orders) {
            orderNumbers.append(order.getOrderNumber()).append(StrUtil.COMMA);
        }
        orderNumbers.deleteCharAt(orderNumbers.length() - 1);
        return ResponseEntity.ok(new OrderNumbersDto(orderNumbers.toString()));
    }

}
